<?php
namespace Modules\Frontend\Controllers;

class TradeBusinessSellController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute() {
		\Components\Utils::isClosedFrontent($this);
	}

	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function freeze() {
		$service = $this -> tradeSecond::getSellServiceInstance() -> find([
			'conditions' => 'status = 3 AND last_time < ' . (time() - 21600)
		]);
		if($service['code'] != 0) {
			return false;
		}
		foreach($service['trade_sell'] as $trade_sell) {
			$serviceUser = $this -> account::getServiceInstance() -> findFirstById($trade_sell -> from_user_id);
			$serviceUser['user'] -> status = 2;
			if(!$serviceUser['user'] -> save())  { throw new \Exception('取消失败'); }

			$this -> status($trade_sell -> trade_sell_id, 6);
		}
	}
	
	public function indexAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$this -> freeze();

		$service = $this -> tradeSecond::getSellServiceInstance() -> pager([
			'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
			'order' => 'status ASC,create_time DESC'
		], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function findFirstByIdAction($id) {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]); }

		$serviceSell = $this -> tradeSecond::getSellServiceInstance() -> findFirstById($id);
		if($serviceSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']); }
		//if($serviceSell['trade_sell'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认收款']); }

		$serviceBuy = $this -> tradeSecond::getBuyServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> trade_buy_id);
		if($serviceBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']); }
		//if($serviceBuy['trade_buy'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已确认收款']); }

		$serviceUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> from_user_id);
		if($serviceUserBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserBuy['code'],'msg'=>$serviceUserBuy['message']]); }
		if($serviceUserBuy['user'] -> pid <= 0) {
			$serviceParentUserBuy['user'] = ['cellphone' => '无推荐人'];
		} else {
			$serviceParentUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceUserBuy['user'] -> pid);
			if($serviceParentUserBuy['code'] != 0) {
				$serviceParentUserBuy['user'] = ['cellphone' => '无推荐人'];
			}
		}

		$serviceBankInfo = $this -> account::getBankInfoServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> user_bank_info_id);
		if($serviceBankInfo['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBankInfo['code'],'msg'=>'银行卡信息获取失败']); }

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'user_buy' =>$serviceUserBuy['user'],'parent_user_buy'=>$serviceParentUserBuy['user'],'trade_buy' => $serviceBuy['trade_buy'],'trade_sell' => $serviceSell['trade_sell'], 'user_bank_info' => $serviceBankInfo['user_bank_info']]);
	}

	public function status($id, $status) {
		$serviceSell = $this -> tradeSecond::getSellServiceInstance() -> findFirstById($id);
		if($serviceSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceSell['code'],'msg'=>'销售订单获取失败']); }
		if($serviceSell['trade_sell'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'销售订单已确认收款']); }

		$serviceBuy = $this -> tradeSecond::getBuyServiceInstance() -> findFirstById($serviceSell['trade_sell'] -> trade_buy_id);
		if($serviceBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceBuy['code'],'msg'=>'进货订单获取失败']); }
		if($serviceBuy['trade_buy'] -> status != 3) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'进货订单已确认收款']); }

		$serviceUserBuy = $this -> account::getServiceInstance() -> findFirstById($serviceBuy['trade_buy'] -> from_user_id);
		if($serviceUserBuy['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserBuy['code'],'msg'=>$serviceUserBuy['message']]); }

		$currentTime = time();
		$this -> db -> begin();
		try {
			switch($status) {
				case 6:
				case '6':
					// 判断0-3小时
					if($serviceBuy['trade_buy'] -> last_time + 10800 >= $currentTime) { $serviceBuy['trade_buy'] -> profit += 5; }
					if($serviceBuy['trade_buy'] -> loop_number == 6) { $serviceBuy['trade_buy'] -> profit = 0; }

					// 加零售积分
					$tradeBuyRetailData = ['type'=>1,'user_id'=>$serviceBuy['trade_buy'] -> from_user_id];
					$tradeBuyRetailData['amount'] = $serviceBuy['trade_buy'] -> amount * ($serviceBuy['trade_buy'] -> profit / 100);
					$tradeBuyRetailData['amount'] += $serviceBuy['trade_buy'] -> amount;
					$serviceRetail = $this -> account::getWalletServiceInstance() -> updateIncAmount($tradeBuyRetailData);
					if($serviceRetail['code'] != 0) { throw new \Exception($serviceRetail['message']); }

					// 加商城积分
					$serviceBuyShop = $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>3,'user_id'=>$serviceBuy['trade_buy'] -> from_user_id,'amount'=>$serviceBuy['trade_buy'] -> amount * 0.05]);
					if($serviceBuyShop['code'] != 0) { throw new \Exception($serviceBuyShop['message']); }

					break;
			}

			$serviceBuy['trade_buy'] -> status = $status;
			$serviceSell['trade_sell'] -> status = $status;

			$serviceBuy['trade_buy'] -> last_time = time();
			$serviceSell['trade_sell'] -> last_time = $serviceBuy['trade_buy'] -> last_time;

			if(!$serviceBuy['trade_buy'] -> save()) { throw new \Exception('确认失败'); }
			if(!$serviceSell['trade_sell'] -> save()) { throw new \Exception('确认失败'); }

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'确认成功']);
	}

		public function statusAction($id, $status) {
			$serviceUserSell = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
			if($serviceUserSell['code'] != 0) { return $this -> response -> setJsonContent(['code'=>$serviceUserSell['code'],'msg'=>$serviceUserSell['message']]); }
	
			$post = $this -> request -> getPost();
			if(!$this -> security -> checkHash($post['safePassword'], $serviceUserSell['user'] -> safe_password)) { return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']); }
	
			return $this -> status($id, $status);
		}

	public function createAction() {
		$post = $this -> request -> getPost();

		if($post['amount'] <= 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于0']);
		}

		if($post['amount'] < 1000) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量不能少于1000']);
		}

		if($post['amount'] > 20000) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'单笔不能超过20000']);
		}

		if(($post['amount'] % 500) != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'数量输入有误']);
		}

		if(!isset($post['user_bank_info_id']) || $post['user_bank_info_id'] <= 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请选择收款账号']);
		}

		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		if(!$this -> security -> checkHash($post['safePassword'], $serviceUser['user'] -> safe_password)) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'安全密码错误']);
		}

		$serviceUserWallet = $this -> account::getWalletServiceInstance() -> findFirstById($serviceUser['user'] -> user_id);
		if($serviceUserWallet['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUserWallet['code'],'msg'=>$serviceUserWallet['message']]);
		}

		$findTradeSell = $this -> tradeSecond::getSellServiceInstance() -> findFirst([
			'conditions' => 'from_user_id = ' . $serviceUser['user'] -> user_id,
			'order' => 'trade_sell_id DESC'
		]);
		if($findTradeSell['code'] == 0 && $findTradeSell['trade_sell'] -> status != 6 && $findTradeSell['trade_sell'] -> status != 7) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'请等候上一单匹配完成']);
		}

		$this -> db -> begin();
		try {
			$serviceBusiness = $this -> account::getWalletServiceInstance() -> updateDecAmount(['type'=>2,'amount'=>$post['amount'],'user_id'=>$serviceUser['user'] -> user_id]);
			if($serviceBusiness['code'] != 0) { throw new \Exception($serviceBusiness['message']); }
			//if($serviceBusiness['code'] != 0) { throw new \Exception('销售失败'); }

			$createTrade = $this -> tradeSecond::getSellServiceInstance() -> create([
				'trade_buy_id' => 0,
				'from_user_id' => $serviceUser['user'] -> user_id,
				'to_user_id' => 0,
				'user_bank_info_id' => $post['user_bank_info_id'],
				'amount' => $post['amount'],
				'original_amount' => $post['amount'],
				'create_time' => time(),
				'last_time' => time(),
				'status' => 0,
			]);
			if($createTrade['code'] != 0) {
				throw new \Exception($createTrade['message']);
			}

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'销售成功']);
	}

	public function cancalAction($id) {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		$findFirstTradeSell = $this -> tradeSecond::getSellServiceInstance() -> findFirst([
			'conditions' => 'trade_sell_id = ' . $id . ' AND from_user_id = ' . $serviceUser['user'] -> user_id
		]);
		if($findFirstTradeSell['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$findFirstTradeSell['code'],'msg'=>$findFirstTradeSell['message']]);
		}
		if($findFirstTradeSell['trade_sell'] -> status != 0) {
			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>'订单操作错误!']);
		}

		$this -> db -> begin();
		try {
			$serviceTrade = $this -> account::getWalletServiceInstance() -> updateIncAmount(['type'=>2,'amount'=>$findFirstTradeSell['trade_sell'] -> amount,'user_id'=>$findFirstTradeSell['trade_sell'] -> from_user_id]);
			if($serviceTrade['code'] != 0) { throw new \Exception('取消失败'); }

			$findFirstTradeSell['trade_sell'] -> trade_buy_id = 0;
			$findFirstTradeSell['trade_sell'] -> to_user_id = 0;
			$findFirstTradeSell['trade_sell'] -> status = 7;
			if(!$findFirstTradeSell['trade_sell'] -> save())  { throw new \Exception('取消失败'); }

			$this -> db -> commit();
		} catch(\Exception $e) {
			$this -> db -> rollback();

			return $this -> response -> setJsonContent(['code'=>-1,'msg'=>$e -> getMessage()]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'取消成功']);
	}
}